import { memo, useState, useEffect, useMemo } from 'react'
import { Avatar, Divider, Layout, theme, ConfigProvider, Flex, Popover, Button, Tooltip, Dropdown, Space, Typography, Input, message, Modal } from 'antd';
const { Title } = Typography;
import { DownOutlined, UserOutlined, AntDesignOutlined, EditOutlined, CheckOutlined, CloseOutlined, UploadOutlined } from '@ant-design/icons';
import React from 'react';
import { useMessage } from '@/hooks/useMessage';
import ImportDocument from '@/components/ImportDocument';
import AddExistingDocModal from '../AddExistingDocModal';
import { useNavigate, useParams } from 'react-router-dom';
import { saveDocMessage, getDocShareCode } from '../api';
import styles from './index.module.less';
import { throttle } from '@/utils/debounceThrottle';

const { Header } = Layout;
const DocDetailHead = ({
    docName,
    setDocName,
    docPermission,
    setDocPermission,
    onSave,
    onAddExistingDocSuccess, 
    onNewDoc
}) => {
    const { success, error, contextHolder } = useMessage();
    const [docContent, setDocContent] = useState({ type: 'doc', content: [] });
    const navigate = useNavigate();
    const { id: knowledgeBaseId, docId } = useParams();

    // 分享模态框状态
    const [shareModalOpen, setShareModalOpen] = useState(false);
    // 分享权限
    const [sharePermission, setSharePermission] = useState('仅阅读');

    // 添加已有文档弹窗状态
    const [addExistingModalVisible, setAddExistingModalVisible] = useState(false);
    const [addExistingLoading, setAddExistingLoading] = useState(false);

    // 判断是否有文档被选中
    const hasSelectedDoc = docId && docId !== 'new';

    // 文档名称
    const [isEditing, setIsEditing] = useState(false);

    // 处理文档名称编辑
    const handleDocNameChange = (e) => {
        setDocName(e.target.value);
    };

    const handleDocNameBlur = () => {
        setIsEditing(false);
        // 这里可以调用API保存文档名称
        // await updateDocName({ name: docName });
    };

    const handleDocNamePressEnter = () => {
        setIsEditing(false);
        // 这里可以调用API保存文档名称
        // await updateDocName({ name: docName });
    };

    // 添加已有文档成功
    const handleAddExistingSuccess = () => {
        setAddExistingModalVisible(false);
        if (typeof onAddExistingDocSuccess === 'function') {
            onAddExistingDocSuccess();
            console.log('onAddExistingDocSuccess:', onAddExistingDocSuccess);
        }
    };

    // 头像
    const UserAvatar = () => {
        return (
            <div className={styles.avatarWrap}>
                <Avatar.Group
                    size="large"
                    max={{
                        count: 2,
                        style: { color: '#f56a00', backgroundColor: '#fde3cf' },
                    }}
                >
                    <Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=3" />
                    <Avatar style={{ backgroundColor: '#f56a00' }}>K</Avatar>
                    <Tooltip title="Ant User" placement="top">
                        <Avatar style={{ backgroundColor: '#87d068' }} icon={<UserOutlined />} />
                    </Tooltip>
                    <Avatar style={{ backgroundColor: '#1677ff' }} icon={<AntDesignOutlined />} />
                </Avatar.Group>
                <Divider />
            </div>
        )
    }

    // 权限按钮 - 根据文档选中状态禁用
    const PermissionsBtn = ({ docPermission }) => {
        const [currTit, setCurrTit] = useState(docPermission || '权限');
        useEffect(() => {
            setCurrTit(docPermission || '权限');
        }, [docPermission]);
        const handleMenuClick = e => {
            const name = e.key
            setCurrTit(name)
            // 如果有 setDocPermission 函数，调用它更新权限
            if (setDocPermission) {
                setDocPermission(name);
            }
        };
        const items = [
            { label: '仅阅读', key: '仅阅读' },
            { label: '可编辑', key: '可编辑' },
            // { label: '可修订', key: '可修订' },
        ];
        const menuProps = {
            items,
            onClick: handleMenuClick,
        };
        return (
            <Space wrap className={styles.permissionsBtn}>
                <Dropdown menu={menuProps}>
                    <Button>
                        <Space>
                            {currTit}
                            <DownOutlined />
                        </Space>
                    </Button>
                </Dropdown>
            </Space>
        )
    }

    // 需要能拿到 docId 和 docPermission
    // 你可以通过 props 传递 docId
    const handleCopyShareCode = async () => {
        if (!docName || !sharePermission) {
            message.error('请先选择分享权限');
            return;
        }
        try {
            const res = await getDocShareCode(docId, sharePermission);
            if (res && res.code === 200 && res.data) {
                await navigator.clipboard.writeText(res.data);
                message.success('分享码已复制到剪贴板');
                // 显示“分享码已复制到剪贴板” 提示后，1s后刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                message.error('获取分享码失败');
            }
        } catch (err) {
            message.error('获取分享码失败');
        }
    };

    // 分享
    const ShareBtn = () => {
        const content = (
            <div className={styles.shareContent}>
                <PermissionsBtn />
                <Flex gap="small" wrap>
                    <Button
                        type="primary"
                        className={styles.shareBtnContainer}
                        onClick={handleCopyShareCode}
                    >
                        复制分享码
                    </Button>
                </Flex>
            </div>
        );
        const buttonWidth = 80;
        const ShareBtn = () => {
            return (
                <Button onClick={() => setShareModalOpen(true)}>
                    分享
                </Button>
            );
        };
        return (
            <Button
                onClick={() => setShareModalOpen(true)}
                disabled={!hasSelectedDoc || docPermission === '仅阅读'}
            >
                分享
            </Button>
        );
    }

    const SaveBtn = () => (
        <Button
            onClick={throttledSave}
            type="primary"
            disabled={ docPermission === '仅阅读'}
        >
            <Space>保存</Space>
        </Button>
    );

    const NewDocBtn = () => (
        <div className={styles.newDocBtn}>
            <Button onClick={onNewDoc}>
                <Space>新建文档</Space>
            </Button>
        </div>
    );

    const AddExistingDocBtn = () => (
        <div className={styles.addExistingDocBtn}>
            <Button onClick={() => setAddExistingModalVisible(true)}>
                <Space>添加已有文档</Space>
            </Button>
        </div>
    );

    // 导入文档成功回调
    const handleImportSuccess = (result) => {
        console.log('导入成功:', result);
        // 刷新文档列表或执行其他操作
        if (typeof onAddExistingDocSuccess === 'function') {
            onAddExistingDocSuccess();
        }
    };

    // 导入文档失败回调
    const handleImportError = (error) => {
        console.error('导入失败:', error);
        // 可以在这里执行错误处理逻辑
    };

    
const throttledCopy = useMemo(() => throttle(handleCopyShareCode, 1000), [handleCopyShareCode]);
const throttledSave = useMemo(() => throttle(onSave, 500), [onSave]);
    return (
        <div className={styles.docDetailHead}>
            {contextHolder}
            <Header className={styles.header}>
                <div className={styles.docNameContainer}>
                    <span className={styles.docNameLabel}>文档名称：</span>
                    {isEditing ? (
                        <Input
                            value={docName}
                            onChange={handleDocNameChange}
                            onBlur={handleDocNameBlur}
                            onPressEnter={handleDocNamePressEnter}
                            className={styles.docNameInput}
                            autoFocus
                            disabled={docPermission === '仅阅读'} // 仅阅读时禁用
                        />
                    ) : (
                        <Title
                            level={4}
                            className={styles.docNameTitle}
                            style={{
                                cursor: docPermission === '仅阅读' ? 'not-allowed' : 'pointer',
                            }}
                            onClick={() => {
                                if (docPermission !== '仅阅读') setIsEditing(true);
                            }}
                        >
                            {docName}
                        </Title>
                    )}
                </div>
                <div className={styles.rightWrap}>
                    <UserAvatar />
                    <NewDocBtn />
                    <AddExistingDocBtn />
                    <div className={styles.importDocBtn}>
                        <ImportDocument
                            onSuccess={handleImportSuccess}
                            onError={handleImportError}
                            folderId=""
                            buttonText="导入文档"
                            buttonProps={{
                                icon: <UploadOutlined />,
                                style: { margin: 5 }
                            }}
                        />
                    </div>
                    <PermissionsBtn docPermission={docPermission} />
                    <ShareBtn></ShareBtn>
                    <SaveBtn></SaveBtn>
                </div>
            </Header>

            {/* 分享Modal */}
            <Modal
                title="分享文档"
                open={shareModalOpen}
                onCancel={() => setShareModalOpen(false)}
                footer={null}
                width={400}
                centered
            >
                <div className={styles.shareModalContent}>
                    {/* 权限选择 */}
                    <div className={styles.permissionSelect}>
                        <span className={styles.permissionLabel}>权限：</span>
                        <Dropdown
                            menu={{
                                items: [
                                    { label: '仅阅读', key: '仅阅读' },
                                    { label: '可编辑', key: '可编辑' },
                                    { label: '可修订', key: '可修订' },
                                ],
                                onClick: (e) => setSharePermission(e.key),
                            }}
                        >
                            <Button>
                                {sharePermission} <DownOutlined />
                            </Button>
                        </Dropdown>
                    </div>
                    <Button
                        type="primary"
                        className={styles.copyShareCodeBtn}
                        onClick={handleCopyShareCode}
                    >
                        复制分享码
                    </Button>
                </div>
            </Modal>

            {/* 添加已有文档弹窗 */}
            <AddExistingDocModal
                visible={addExistingModalVisible}
                onCancel={() => setAddExistingModalVisible(false)}
                onConfirm={handleAddExistingSuccess}
                loading={addExistingLoading}
                knowledgeBaseId={knowledgeBaseId}
            />
        </div>
    );
}

export const MemoDocDetailHead = memo(DocDetailHead)